<?php

/***************************************************************************
 *   Copyright (C) 2010 by Math2Gold,Twitter @math2gold                    *
 *   math2gold#gmail.com                                                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


class simple_talk {
	public $ci;
	public $http_code;
	public $http_info;
	public $login_ref;

	public $since_id;
	public $current_hash;

	function __construct()
	{
		$this->ci=curl_init();
		$this->current_hash="";
		$this->since_id=NULL;
	}

	function flush_cookie()
	{
		$this->close();
		$this->ci=curl_init();
	}

	function close()
	{
		curl_close($this->ci);
	}

	function setup_conn_base($url)
	{
	    curl_setopt($this->ci, CURLOPT_USERAGENT, "math2gold simple_talk v1.0");
	    curl_setopt($this->ci, CURLOPT_CONNECTTIMEOUT, 30);
	    curl_setopt($this->ci, CURLOPT_TIMEOUT,30);
	    curl_setopt($this->ci, CURLOPT_RETURNTRANSFER, TRUE); //must keep
	    curl_setopt($this->ci, CURLOPT_URL, $url);
	    curl_setopt($this->ci, CURLOPT_POST, 0);
	    curl_setopt($this->ci, CURLOPT_FOLLOWLOCATION , 1);
	    curl_setopt($this->ci, CURLOPT_HEADER, 0);	
	    curl_setopt($this->ci, CURLOPT_COOKIEFILE , "cookie.ck");
	    curl_setopt($this->ci, CURLOPT_COOKIEJAR , "cookie.ck");
	    $this->url = $url;
	}

	function check_login_result()
	{
		return (NULL!=strstr($this->response,"Location: ".$this->login_ref));
	}

	function exec_conn()
	{
	   $this->http_info=array();
	    $this->response = curl_exec($this->ci);
	    $this->http_code = curl_getinfo($this->ci, CURLINFO_HTTP_CODE);
	    $this->http_info = array_merge($this->http_info, curl_getinfo($this->ci));
	}

	function load_data($url,$followlocation=1)
	{
                $this->setup_conn_base($url);
                curl_setopt($this->ci, CURLOPT_FOLLOWLOCATION , $followlocation);
                $this->exec_conn();
	}

	function upload_file($url,$filename,$maxsize=100000)
	{
	    $fs=filesize($filename);
            if (empty($fs)) return NULL;
	    if ($fs>$maxsize) return NULL;
            $this->setup_conn_base($url);
	    curl_setopt($this->ci, CURLOPT_POST, true);
	    $post = array(
        	"userfile"=>"@".$filename,
	    );
	    curl_setopt($this->ci, CURLOPT_POSTFIELDS, $post); 
            $this->exec_conn();
            return $this->http_code;
	}
	
	function load_chat($url)
	{
		$this->load_data($url);
		return json_decode($this->response);
	}

	function send_chat($url,$msg,$inreply=0,$mtype=0)
	{
		$s=array();
		$s["msg"]=$msg;
		$s["inreply"]=$inreply;
		$s["mtype"]=$mtype;
		$send=json_encode($s);
		$this->setup_conn_base($url);	
		curl_setopt($this->ci, CURLOPT_POST, 1);	
		curl_setopt ($this->ci, CURLOPT_POSTFIELDS, $send);
		curl_setopt($this->ci, CURLOPT_HTTPHEADER, array("Content-Type: text/x-json","Content-length: ".strlen($send))); 
		$this->exec_conn();
		return json_decode($this->response);
	}

	function construct_load_url($url_base,$hash,$since_id=NULL)
	{
		if ($hash)
		{
			return $url_base."?hash=1";
		}
		else
		{
			if ($since_id==NULL)
			{
				return $url_base;
			}
			else
			{
				return $url_base."?since=".$since_id;
			}
		}
	}

	function load_new_chat($url_base)
	{
		$ret=$this->load_chat($this->construct_load_url($url_base,true));
		if (isset($ret->{"digest"}))
		{
			if ( $ret->{"digest"}!=$this->current_hash)
			{
				$ret=$this->load_chat($this->construct_load_url($url_base,false,$this->since_id));
				if (isset($ret->{"digest"}))
				{
					$msgs=$ret->{"msgs"};
					if (count($msgs)>0)
					{
					$r=array();
					foreach ($msgs as $m)
					{
						if ($m->{"id"}<=$this->since_id) break;
						$r[]=$m;
					}
					$this->since_id=$msgs[0]->{"id"};
					$this->current_hash=$ret->{"digest"};
					return $r;	
					}
				}
			}
		}

		if (isset($ret) && isset($ret->{"res"}) && ("".$ret->{"res"})!="0")	
		{
			return $ret;
		}
		return false;	
	}
};

class fandong_simple_talk
{
	public $st;

	public $url_send='http://api.fandong.org/send_chat.php';
	public $url_recv='http://api.fandong.org/list_chat.php';
	public $url_sendimg='http://api.fandong.org/upload.php';
	public $limit_sendimg=100000;

	public $login_check_func="bbpress_base";
	public $loginparam;//
	
	public function __construct()
	{
		$this->st=new simple_talk;
	}

	function config($params)
	{
		$this->url_send=$params->send;
		$this->url_recv=$params->recv;
		$this->url_sendimg=$params->sendimg;
		$this->limit_sendimg=$params->maximgsize;
		$this->login_check_func=$params->loginmethod;
		$this->loginparam=$params->loginparam;
	}
	
	function get_config_by_url($url)
	{
		$this->st->load_data($url);
		if ($this->st->http_code==200)
		{
			return json_decode($this->st->response);
		}
		return NULL;
	}

        function check_login_bbpress_result($ref)
        {
                return (NULL!=strstr($this->st->response,"Location: ".$ref));
        }

	function _login_bbpress_base_core($url,$user,$password,$ref)
	{
		$this->st->setup_conn_base($url);
	    	curl_setopt($this->st->ci, CURLOPT_FOLLOWLOCATION , 0);
		curl_setopt($this->st->ci, CURLOPT_POST, 1);	
		curl_setopt($this->st->ci, CURLOPT_HEADER, 1);	
		curl_setopt ($this->st->ci, CURLOPT_POSTFIELDS, "password=".urlencode($password)."&user_login=".urlencode($user)."&re=&_wp_http_referer=".urlencode($ref));
		$this->st->exec_conn();
		return $this->check_login_bbpress_result($ref);
	}

	public function login_bbpress_base()
	{
		$ret= $this->_login_bbpress_base_core($this->loginparam->url,$this->loginparam->uname,$this->loginparam->pwd,$this->loginparam->ref);
		$this->st->flush_cookie();
		return $ret;
	}

	public function login()
	{
		return $this->{"login_".$this->login_check_func}();
	}

	public function core()
	{
		return $this->st;
	}

	public function close()
	{
		$this->st->close();
	}

	public function send($msg,$inreply=0,$mtype=0)
	{
		$r=$this->st->send_chat($this->url_send,$msg,$inreply,$mtype);
		if (isset($r) && $r!=false && isset($r->{'res'}) && "".($r->{'res'})=="-11111")
		{
			$r1=$this->login();
			if ($r1)
			{
				$r=$this->st->send_chat($this->url_send,$msg,$inreply,$mtype);
			}
		}
		return $r;
	}

	public function recv()
	{
		$r=$this->st->load_new_chat($this->url_recv);
		if (isset($r) && $r!=false && isset($r->{'res'}) && "".($r->{'res'})=="-11111")
		{
			$r1=$this->login();
			if ($r1)
			{
				$r=$this->st->load_new_chat($this->url_recv);
			}
		}
		return $r;
	}

	public function send_img($file)
	{
		$p=getimagesize($file);
		if (empty($p)) return NULL;
		return $this->st->upload_file($this->url_sendimg,$file,$this->limit_sendimg);
	}
};

